package com.idb.listener;

import cn.hutool.log.Log;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class IdbPluginListener implements ApplicationListener<ApplicationStartingEvent>, Ordered {
    static private final Log log = Log.get(IdbPluginListener.class);
    @Override
    public void onApplicationEvent(ApplicationStartingEvent event) {
        try {
            URLClassLoader classLoader = (URLClassLoader) IdbPluginListener.class.getClassLoader();
            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            File libDir = new File("plugins");
            File[] jarFiles = libDir.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.endsWith(".jar");
                }
            });
            if (jarFiles != null) {
                for (File jarFile : jarFiles) {
                    method.invoke(classLoader, jarFile.toURI().toURL());
                }
            }
        } catch (Exception e) {
            log.error("加载插件失败",e);
        }
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
